package cn.bdqn.page1;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.Scanner;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * 话费充值类
 */
public class AddMoney {
	// 因为所有的方法都需要DOM树
	static Document document = null;
	static Element root = null;

	// 保存用户信息类
	public static void save(String path) {
		OutputFormat format = null;
		XMLWriter writer = null;
		try {
			format = OutputFormat.createPrettyPrint();
			writer = new XMLWriter(new FileWriter("UserMessage.xml"), format);
			writer.write(document);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				writer.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	// 话费充值
	public void add() throws DocumentException {
		Scanner input = new Scanner(System.in);
		System.out.print("请输入充值卡号：");
		String phone = input.next();
		System.out.print("请输入充值金额：");
		double money = input.nextDouble();
		SAXReader reader = new SAXReader();
		document = reader.read("UserMessage.xml");
		root = (Element) document.getRootElement();
		Iterator itUser = root.elementIterator();
		while (itUser.hasNext()) {
			Element user = (Element) itUser.next();
			if (phone.equals(user.attributeValue("id"))) {
				AddMoney am = new AddMoney();
				Double balance = Double.parseDouble(user
						.attributeValue("balance"));
				// 老是会报空指针异常！！！！！！
				balance = balance + money;
				user.attribute("balance").setValue(
						(new Double(balance)).toString());
				System.out.println("充值成功，当前话费余额为" + balance + "元。");
			}
		}
		save("UserMessage.xml");
	}
}
